#include "singlefileexporttask.h"
#include "unifiedpagerenderer.h"
#include "configmanager.h"
#include "logindialog.h"
#include <QtCore/QDebug>
#include <QtGui/QPdfWriter>
#include <QtGui/QPainter>
#include <QtWidgets/QApplication>
#include <QtGui/QPageLayout>
#include <QtGui/QPageSize>
#include <QtCore/QMargins>
#include "dpiservice.h"
SingleFileExportTask::SingleFileExportTask(const UnifiedFileInfo& fileInfo,
                                           const ProcessingSettings& settings,
                                           const QString& outputPath,
                                           int startPageNumber,
                                           UnifiedPageRenderer* renderer,
                                           QObject* parent)
    : QObject(parent)
    , m_fileInfo(fileInfo)
    , m_settings(settings)
    , m_outputPath(outputPath)
    , m_startPageNumber(startPageNumber)
    , m_renderer(renderer)
    , m_pdfWriter(nullptr)
{
    // 设置任务自动删除
    setAutoDelete(true);
}
SingleFileExportTask::~SingleFileExportTask()
{
    if (m_pdfWriter) {
        delete static_cast<QPdfWriter*>(m_pdfWriter);
        m_pdfWriter = nullptr;
    }
}
void SingleFileExportTask::run()
{
    if (!m_renderer) {
        m_lastError = "统一渲染器未设置";
        emit exportFailed(m_fileInfo.filePath, m_lastError);
        return;
    }
    bool success = exportToPDF();
    if (success) {
        emit exportCompleted(m_fileInfo.filePath);
    } else {
        emit exportFailed(m_fileInfo.filePath, m_lastError);
    }
}
bool SingleFileExportTask::exportToPDF()
{
    // 初始化PDF写入器
    if (!initializePDFWriter()) {
        return false;
    }
    QPdfWriter* pdfWriter = static_cast<QPdfWriter*>(m_pdfWriter);
    QPainter painter;
    if (!painter.begin(pdfWriter)) {
        m_lastError = "无法开始PDF绘制";
        return false;
    }
    // 逐页写入PDF
    for (int pageIndex = 0; pageIndex < m_fileInfo.pageCount; ++pageIndex) {
        if (pageIndex > 0) {
            // 添加新页面
            if (!pdfWriter->newPage()) {
                m_lastError = QString("无法创建第 %1 页").arg(pageIndex + 1);
                painter.end();
                return false;
            }
        }
        // 写入当前页面 - 传递painter引用
        if (!writePageToPDF(pageIndex, &painter)) {
            painter.end();
            return false;
        }
        // 更新进度
        int progress = (pageIndex + 1) * 100 / m_fileInfo.pageCount;
        emit progressUpdated(m_fileInfo.filePath, pageIndex + 1, m_fileInfo.pageCount);
    }
    painter.end();
    return finalizePDFWriter();
}
bool SingleFileExportTask::initializePDFWriter()
{
    QPdfWriter* pdfWriter = new QPdfWriter(m_outputPath);
    m_pdfWriter = pdfWriter;
    // 设置页面布局
    QPageLayout pageLayout(QPageSize(QPageSize::A4), QPageLayout::Portrait, QMargins());
    pdfWriter->setPageLayout(pageLayout);
    // 设置分辨率
    pdfWriter->setResolution(m_settings.standardDPI);
    // 设置元数据（在标题中加入DPI，便于核验）
    pdfWriter->setCreator("LongImageReader");
    pdfWriter->setTitle(QString("Export: %1 (DPI=%2)").arg(m_fileInfo.fileName).arg(m_settings.standardDPI));
    return true;
}
bool SingleFileExportTask::writePageToPDF(int pageIndex, QPainter* painter)
{
    QPdfWriter* pdfWriter = static_cast<QPdfWriter*>(m_pdfWriter);
    // 获取页面尺寸
    QRect pageRect = pdfWriter->pageLayout().paintRect(QPageLayout::Point).toRect();
    // 计算全局页码
    int globalPageNumber = calculateGlobalPageNumber(pageIndex);
    // 渲染当前页面的图像内容
    QImage pageImage = renderPage(pageIndex);
    if (pageImage.isNull()) {
        m_lastError = QString("页面 %1 内容渲染失败").arg(pageIndex + 1);
        return false;
    }
    // 使用新的双画布渲染接口渲染页面
    try {
        // 使用新的双画布接口：直接传递图像内容
        m_renderer->renderToPDF(pdfWriter, painter, pageImage, globalPageNumber, m_fileInfo.pageCount);

        // === 倒置水印逻辑：默认添加水印，授权验证通过后才不添加 ===
        bool shouldAddWatermark = true;  // 默认添加水印
        
        // 多层验证：只有通过所有验证才不添加水印
        QString authToken = ConfigManager::getAuthToken();
        if (!authToken.isEmpty()) {
            // Token存在，进一步验证用户类型
            bool isTrialUser = LoginDialog::isTrialUser();
            if (!isTrialUser) {
                // 不是试用用户，允许无水印导出
                shouldAddWatermark = false;
            } else {
            }
        } else {
        }
        
        // 应用水印（如果需要）
        if (shouldAddWatermark) {
            // 使用清晰的水印设置
            painter->save();

            // 设置水印字体和样式
            QFont watermarkFont("Microsoft YaHei", 36, QFont::Bold); // 更大的字体
            painter->setFont(watermarkFont);
            painter->setPen(QColor(200, 200, 200, 120)); // 浅灰色，透明度适中
            painter->setRenderHint(QPainter::Antialiasing, true);

            // 计算水印位置（3x3网格布局）
            QRect pageRect = painter->viewport();
            int watermarkWidth = pageRect.width() / 3;
            int watermarkHeight = pageRect.height() / 3;

            // 水印文字
            QString watermarkText = "影谷长图处理大师";

            // 在3x3网格中添加水印
            for (int row = 0; row < 3; ++row) {
                for (int col = 0; col < 3; ++col) {
                    int x = col * watermarkWidth + watermarkWidth / 2;
                    int y = row * watermarkHeight + watermarkHeight / 2;

                    // 保存 painter 状态
                    painter->save();

                    // 移动到水印位置并旋转45度
                    painter->translate(x, y);
                    painter->rotate(45);

                    // 绘制水印文字
                    QRect textRect = painter->fontMetrics().boundingRect(watermarkText);
                    textRect.moveCenter(QPoint(0, 0));
                    painter->drawText(textRect, Qt::AlignCenter, watermarkText);

                    // 恢复 painter 状态
                    painter->restore();
                }
            }

            painter->restore();
        }

        return true;
    } catch (const std::exception& e) {
        m_lastError = QString("双画布PDF渲染失败 - 页面 %1: %2").arg(pageIndex + 1).arg(e.what());
        // 如果双画布渲染失败，降级到传统方法
        try {
            m_renderer->setPageContent(pageImage);
            m_renderer->renderToPDF(pdfWriter, painter, globalPageNumber);

            // === 倒置水印逻辑（传统渲染）：默认添加水印，授权验证通过后才不添加 ===
            bool shouldAddWatermark = true;  // 默认添加水印
            
            // 多层验证：只有通过所有验证才不添加水印
            QString authToken = ConfigManager::getAuthToken();
            if (!authToken.isEmpty()) {
                // Token存在，进一步验证用户类型
                bool isTrialUser = LoginDialog::isTrialUser();
                if (!isTrialUser) {
                    // 不是试用用户，允许无水印导出
                    shouldAddWatermark = false;
                } else {
                }
            } else {
            }
            
            // 应用水印（如果需要）
            if (shouldAddWatermark) {
                // 使用清晰的水印设置
                painter->save();

                // 设置水印字体和样式
                QFont watermarkFont("Microsoft YaHei", 36, QFont::Bold); // 更大的字体
                painter->setFont(watermarkFont);
                painter->setPen(QColor(200, 200, 200, 120)); // 浅灰色，透明度适中
                painter->setRenderHint(QPainter::Antialiasing, true);

                // 计算水印位置（3x3网格布局）
                QRect pageRect = painter->viewport();
                int watermarkWidth = pageRect.width() / 3;
                int watermarkHeight = pageRect.height() / 3;

                // 水印文字
                QString watermarkText = "影谷长图处理大师";

                // 在3x3网格中添加水印
                for (int row = 0; row < 3; ++row) {
                    for (int col = 0; col < 3; ++col) {
                        int x = col * watermarkWidth + watermarkWidth / 2;
                        int y = row * watermarkHeight + watermarkHeight / 2;

                        // 保存 painter 状态
                        painter->save();

                        // 移动到水印位置并旋转45度
                        painter->translate(x, y);
                        painter->rotate(45);

                        // 绘制水印文字
                        QRect textRect = painter->fontMetrics().boundingRect(watermarkText);
                        textRect.moveCenter(QPoint(0, 0));
                        painter->drawText(textRect, Qt::AlignCenter, watermarkText);

                        // 恢复 painter 状态
                        painter->restore();
                    }
                }

                painter->restore();
            }

            return true;
        } catch (const std::exception& fallbackError) {
            m_lastError = QString("传统PDF渲染也失败 - 页面 %1: %2").arg(pageIndex + 1).arg(fallbackError.what());
            return false;
        }
    } catch (...) {
        m_lastError = QString("页面 %1 渲染失败: 未知错误").arg(pageIndex + 1);
        return false;
    }
}
bool SingleFileExportTask::finalizePDFWriter()
{
    // PDF写入器会在析构时自动完成文件写入
    return true;
}
QImage SingleFileExportTask::renderPage(int pageIndex)
{
    if (!m_renderer) {
        QImage placeholder(800, 600, QImage::Format_RGB32);
        placeholder.fill(Qt::white);
        return placeholder;
    }
    // 使用UnifiedPageRenderer来渲染页面内容
    // 这应该与主窗口显示使用相同的渲染逻辑
    // 创建临时图像进行渲染：按导出DPI计算A4像素尺寸
    const QSize a4ExportSize = DpiSvc.calculateA4PixelSize(DpiService::DpiPurpose::PdfExport);
    QImage pageImage(a4ExportSize, QImage::Format_RGB32);
    pageImage.fill(Qt::white);
    QPainter painter(&pageImage);
    QRect targetRect = pageImage.rect();
    int globalPageNumber = calculateGlobalPageNumber(pageIndex);
    // 这里需要实际的页面渲染逻辑
    // TODO: 需要从文件中获取实际的页面内容，应该与主窗口显示逻辑一致
    m_renderer->renderToWidget(&painter, targetRect, globalPageNumber);
    return pageImage;
}
int SingleFileExportTask::calculateGlobalPageNumber(int localPageIndex) const
{
    return m_startPageNumber + localPageIndex;
}